package com.dabai.iot.core.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dabai.common.core.utils.ObjectUtils;
import com.dabai.common.redis.utils.RedisUtils;
import com.dabai.common.tenant.helper.TenantHelper;
import com.dabai.iot.core.cache.CacheKey;
import com.dabai.iot.core.entity.AlarmActionEntity;
import com.dabai.iot.core.mapper.AlarmActionMapper;
import com.dabai.iot.core.service.IAlarmActionService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 告警动作输出 Service 实现类
 *
 * @author kev1n
 */
@Service
public class AlarmActionServiceImpl extends ServiceImpl<AlarmActionMapper, AlarmActionEntity> implements IAlarmActionService {

    @Override
    public List<AlarmActionEntity> getAlarmActionsByAlarmId(Long alarmId) {
        return this.lambdaQuery()
            .eq(AlarmActionEntity::getAlarmId, alarmId)
            .list();
    }

    @Override
    public List<AlarmActionEntity> getAlarmActionsCacheByAlarmId(Long alarmId) {
        String cacheKey = CacheKey.getAlarmActionsKey(alarmId);
        List<AlarmActionEntity> alarmActionsCache = TenantHelper.ignore(() -> RedisUtils.getCacheList(cacheKey));
        if (ObjectUtils.isNotEmpty(alarmActionsCache)) {
            return alarmActionsCache;
        }

        List<AlarmActionEntity> alarmActionList = getAlarmActionsByAlarmId(alarmId);
        if (ObjectUtils.isNotEmpty(alarmActionList)) {
            alarmActionsCache = alarmActionList;
            TenantHelper.ignore(() -> RedisUtils.setCacheList(cacheKey, alarmActionList));
        }

        return alarmActionsCache;
    }

    @Override
    public void removeAlarmActions(Long alarmId) {
        this.remove(Wrappers.<AlarmActionEntity>query().lambda().eq(AlarmActionEntity::getAlarmId, alarmId));
        String cacheKey = CacheKey.getAlarmActionsKey(alarmId);
        TenantHelper.ignore(() -> RedisUtils.deleteObject(cacheKey));
    }

}
